/*
** check_param.c for asm in /home/vanet_c//proj-kw/asm
** 
** Made by charles-edouard vanet
** Login   <vanet_c@epitech.net>
** 
** Started on  Thu Dec  6 12:29:54 2012 charles-edouard vanet
** Last update Sat Dec 15 17:40:24 2012 charles-edouard vanet
*/

#include	"../includes/asm.h"

int	check_nb_param(char *str, int nb_param)
{
  int	result;
  int	len;

  len = 0;
  result = 0;
  while (str[len])
    {
      if (char_cmp(str[len], ',') == 0 || char_cmp(str[len], ' ') == 0)
	result++;
      if (str[len] == ',' && str[len + 1] == ' ')
	len++;
      len++;
    }
  if (result == nb_param)
    return (0);
  return (2);
}

char	*get_line_name(char *instruction)
{
  int	i;
  char	*result;
  int	c;

  c = 0;
  while (instruction[c] != '\0' && instruction[c] != ' '
	 && instruction[c] != ':')
    c++;
  i = 0;
  if ((result = malloc(c + 1)) == NULL)
    my_error("", "", "Can't perform malloc.\n", 1);
  if (instruction[0] == ':' || instruction[c] == ':')
    {
      free(result);
      return (NULL);
    }
  while (instruction[i] != '\0' && instruction[i] != ' ')
    {
      result[i] = instruction[i];
      i++;
    }
  result[i] = '\0';
  return (result);
}

int		check_name(char *instruction)
{
  int		i;
  char		**name;
  static int	nb_param[] = {
    1, 2, 2, 3, 3, 3, 3, 3, 1, 3, 3, 1, 2, 3, 1, 1};
  char		*line_name;

  i = -1;
  if (instruction[0] == '.' || instruction[0] == '\0')
    return (0);
  if ((line_name = get_line_name(instruction)) == NULL)
    return (0);
  name = init_tab(name);
  while (name[++i] != 0)
    if (my_strcmp(name[i], line_name) == 0)
      {
	free(line_name);
	my_free_tab(name);
	return (check_nb_param(instruction, nb_param[i]));
      }
  free(line_name);
  my_free_tab(name);
  return (1);
}

int	check_file(char *file)
{
  int	i;
  int	result;

  i = 0;
  result = 1;
  if (open(file, O_RDONLY) == -1)
    return (1);
  while (file[i])
    {
      if (file[i] == '.')
	{
	  if (file[i + 1] == 's' && file[i + 2] == '\0')
	    result = 0;
	  else
	    result = 2;
	}
      i++;
    }
  return (result);
}

void	check_instruction(char *file, t_list **file_list, int file_number, int fd)
{
  char	*instruction;
  int	check_l;
  int	line_nb;
  int	line_wit_error;
  int	check_l_save;

  line_wit_error = 0;
  line_nb = 0;
  while ((instruction = get_next_line(fd, file_number)))
    {
      line_nb++;
      instruction = epur_comments(instruction);
      if (((check_l = check_name(instruction)) == 0) && instruction != NULL)
	processing(instruction, line_nb, file_list);
      else if (line_wit_error == 0)
	{
	  line_wit_error = line_nb;
	  check_l_save = check_l;
	}
      free(instruction);
    }
  if (line_wit_error > 0)
    check_instru_msg(file_list, line_wit_error, check_l_save);
  init_compilateur(file_list);
  return ;
}
